package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

/**
 * ClassName MyInitSeckillProductJob
 * Create by Mike
 * Date 2021/10/22 20:41
 */
@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Override
    public void execute(ShardingContext shardingContext) {
        /*System.out.println(shardingContext.getShardingParameter());*/
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {
        //1.远程调用我们的秒杀服务把数据查询出来,Result data:List<SeckillProductVO>=
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTime(Integer.parseInt(time));
        /**
         * result 的数据一共有几种情况
         * 1.一种情况秒杀服务直接挂掉了,直接走降级的方法返回值为null
         * 2.第二个中服务调用没问题 {code:200 msg:"操作成功",data:list}
         * 3.第三种情况 秒杀服务内部出现问题 {code:50201,msg:"秒杀服务繁忙"}
         */
        if (result != null && !result.hasError()){
            final List<SeckillProductVo> seckillProductVos = result.getData();
            if (seckillProductVos != null && seckillProductVos.size() > 0){
                //2.把查询出来的数据放在redis中
                for (SeckillProductVo seckillProductVo : seckillProductVos) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),
                            seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");

                }
                System.out.println("数据同步成功:" + time);
            }
        }
    }
}
